﻿using Common;
using DevExpress.XtraEditors;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Serialization;

public class XmlUtil
{
    /// <summary>  
    /// 将object对象序列化成XML  
    /// </summary>  
    /// <typeparam name="T">需要序列化的对象</typeparam>  
    /// <param name="encoding">如果序列化出错，可以尝试修改下encoding的值试试</param>  
    /// <returns></returns>  
    public static string ObjectToXML<T>(T t, Encoding encoding)
    {
        try
        {
            XmlSerializer ser = new XmlSerializer(t.GetType());
            using (MemoryStream mem = new MemoryStream())
            {
                using (XmlTextWriter writer = new XmlTextWriter(mem, encoding))
                {
                    XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
                    ns.Add("", "");
                    ser.Serialize(writer, t, ns);

                    //越过BOM
                    string rst = encoding.GetString(mem.ToArray()).StartsWith("<") ? encoding.GetString(mem.ToArray()) : encoding.GetString(mem.ToArray()).Substring(1);
                    return rst;
                }
            }
        }
        catch (Exception)
        {
            return "";
        }
    }

    /// <summary>  
    /// 将XML反序列化成对象  
    /// </summary>  
    /// <typeparam name="T"></typeparam>  
    /// <param name="source">需要序列化的XML字符串</param>  
    /// <param name="encoding">如果序列化出错，可以尝试修改下encoding的值试试</param>  
    /// <returns></returns>  
    public static T XMLToObject<T>(string source, Encoding encoding)
    {
        //越过BOM
        string strSource = ToIsNULLString(source);
        source = strSource.StartsWith("<") ? strSource : strSource.Substring(1);
        try
        {
            XmlSerializer mySerializer = new XmlSerializer(typeof(T));
            using (MemoryStream stream = new MemoryStream(encoding.GetBytes(source.Replace("utf-16", "utf-8"))))
            {
                return (T)mySerializer.Deserialize(stream);
            }
        }
        catch (Exception)
        {
            return default(T);
        }
    }
    public static string ToIsNULLString(string self)
    {
        if (self == null)
        {
            return "";
        }
        return self.ToString();
    }


    public static XmlDocument LoadXML(string path)
    {
        XmlDocument xml = null;
        try
        {
            if (!string.IsNullOrEmpty(path))
            {
                xml = new XmlDocument();
                xml.Load(path);
            }
        }
        catch (Exception)
        {
            return null;
        }

        return xml;
    }

    /// <summary>
    /// 根据TagId 、属性名称获取属性值
    /// </summary>
    /// <param name="doc"></param>
    /// <param name="TagName">如体温单：TemperatureChart</param>
    /// <param name="AttrName">获取标题传Text</param>
    /// <returns></returns>
    public static string GetAttributValue(XmlDocument doc, string TagId, string AttrName)
    {
        if (doc == null || doc.Attributes.Count == 0)
        {
            return "";
        }

        XmlElement ele = doc.GetElementById(TagId);
        if (ele != null) { return ele.Attributes[AttrName] == null ? "" : ele.Attributes[AttrName].Value; }
        return "";
    }

    /// <summary>
    /// 根据TagId 、属性名称修改、设置属性值
    /// </summary>
    /// <param name="doc"></param>
    /// <param name="TagId"></param>
    /// <param name="AttrName"></param>
    public static void SetAttributValue(XmlDocument doc, string TagId, string AttrName, string Value)
    {
        if (doc == null || doc.Attributes.Count == 0)
        {
            return;
        }

        XmlElement ele = doc.GetElementById(TagId);
        if (ele != null && ele.HasAttribute(AttrName))
        {
            ele.SetAttribute(AttrName, Value);
        }
    }

    /// <summary>
    /// 在某节点下添加一个子节点
    /// </summary>
    /// <param name="TagName"></param>
    /// <param name="Id"></param>
    /// <param name="?"></param>
    public void AddElement(XmlDocument doc, string ParentTagName, string ChildTagName, string TagId)
    {
        if (doc == null || doc.Attributes.Count == 0)
        {
            return;
        }

        XmlNodeList ele = doc.GetElementsByTagName(ParentTagName);
        if (ele != null && ele.Count > 0)
        {
            XmlNode xmlnode = doc.CreateNode(XmlNodeType.Element, ChildTagName, "");
            ele[0].AppendChild(xmlnode);
        }

    }

    /// <summary>
    /// 根据Id删除某节点
    /// </summary>
    /// <param name="doc"></param>
    /// <param name="TagName"></param>
    /// <param name="Id"></param>
    public void RemoveElement(XmlDocument doc, string TagName, string Id)
    {
        XmlNodeList ele = doc.GetElementsByTagName(TagName);
        XmlElement x = doc.GetElementById(Id);
        ele[0].ParentNode.RemoveChild(x);
    }

    /// <summary>
    /// 获取文书下拉框的配置信息
    /// </summary>
    /// <returns></returns>
    public static XmlDocument GetItems()
    {
        XmlDocument xmlDoc = new XmlDocument();
        try
        {
            if (File.Exists(System.Windows.Forms.Application.StartupPath + @"\CommonConfig.xml"))
            {
                xmlDoc = XmlUtil.LoadXML(System.Windows.Forms.Application.StartupPath + @"\CommonConfig.xml");
            }
            else
                xmlDoc = XmlUtil.LoadXML("../../CommonConfig.xml");
        }
        catch (Exception ex)
        {
            WriteLog.WriteLogString("加载CommonConfig.xml失败：" + ex.Message);
            XtraMessageBox.Show("加载CommonConfig.xml失败");
        }
        return xmlDoc;
    }
}